<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="toggle" label-width="68px">
      <el-form-item label="歌名" prop="username">
        <el-input v-model="queryParams.name" placeholder="请输入您要查询的歌名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="歌手" prop="singer">
        <el-input v-model="queryParams.singer" placeholder="请输入您要查询的歌手" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="热度" prop="hot">
        <el-select v-model="queryParams.hot" placeholder="请选择热度">
          <el-option label="热曲" value="是"></el-option>
          <el-option label="一般" value="否"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除
        </el-button>
      </el-col>
      <div class="right-toolbar">
        <el-tooltip class="item" effect="dark" :content="toggle ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="toggle = !toggle" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getList" />
        </el-tooltip>
      </div>
    </el-row>

    <el-table :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="80" sortable />
      <el-table-column label="歌名" align="center" prop="name">
        <template slot-scope="scope">
          <el-link type="primary" @click="goto(base_api + scope.row.content)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="歌手" align="center" prop="singer" />
      <el-table-column label="热度" align="center" prop="hot" sortable>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.hot === '是'">热曲</el-tag>
          <el-tag type="success" v-if="scope.row.hot === '否'">一般</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.hot === '否'" size="mini" type="text" icon="el-icon-top"
            @click="handleHot(scope.row)">上热度
          </el-button>
          <el-button v-else size="mini" type="text" icon="el-icon-bottom" @click="handleHot(scope.row)">下热度
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-chat-line-square"
            @click="handleComment(scope.row)">评论</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="queryParams.pageSize"
      layout="->,total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="歌名" prop="name">
          <el-input v-model="form.name" placeholder="请输入歌名" />
        </el-form-item>
        <el-form-item label="歌手" prop="singer">
          <el-input v-model="form.singer" placeholder="请输入歌手" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-upload class="upload-demo" :action="uploadApi" :limit="1" :file-list="contentList"
            :on-success="(res, file, fileList) => handleUploadSuccess(res, file, fileList, 'RESUME')"
            :before-upload="(file) => handleBeforeUpload(file, 'RESUME')"
            :on-remove="(file, fileList) => handleRemove(file, fileList, 'RESUME')">
            <el-button size="small" type="primary">这里点击上传音乐</el-button>
            <div slot="tip" class="el-upload-tip">请上传大小不超过 <b>1MB</b> 的 <b>mp3</b>音乐</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addMusic, deleteMusics, getMusicList, updateMusic } from "@/api/song";

const BASE_API = process.env.VUE_APP_BASE_API
const UPLOAD_API = BASE_API + 'music/file/upload'
export default {
  name: "User",
  watch: {
    // 监听resume构造resumeList
    'form.content': {
      handler(val) {
        if (!val) {
          this.contentList = []
          return
        }
        const arr = val.toString().split("/")
        const name = arr[1]
        this.contentList = [{
          name: name,
          url: val
        }]
      }
    }
  },
  data() {
    return {
      base_api: BASE_API,
      uploadApi: UPLOAD_API,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        singer: null,
        hot: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [{ required: true, message: '请输入歌名', trigger: 'blur' }],
        singer: [{ required: true, message: '请输入歌手', trigger: 'blur' }],
      },
      toggle: true,
      contentList: []
    }
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      getMusicList(this.queryParams).then(res => {
        this.userList = res.data.list
        this.total = res.data.count
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: null,
        singer: null
      };
      this.contentList = []
      this.$nextTick(() => {
        this.$refs.form.resetFields()
        this.$refs.form.clearValidate()
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        username: null
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加歌曲";
      this.form.hot = '否'
    },
    /** 修改热度 */
    handleHot(row) {
      getMusicList({
        id: row.id.toString()
      }).then(response => {
        row = response.data.list[0];
        row.hot = (row.hot === '否') ? '是' : '否'
      }).then(() => {
        updateMusic(row).then(() => {
          if (row.hot === '是') {
            this.$message.success("热度上升")
          } else {
            this.$message.info("热度下降")
          }
          this.getList()
        });
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ids = row.id || this.ids
      getMusicList({
        id: ids.toString()
      }).then(response => {
        this.form = response.data.list[0];
        this.open = true;
        this.title = "修改歌曲";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMusic(this.form).then(() => {
              this.$message.success("修改成功")
              this.open = false;
              this.getList();
              this.reset();
            });
          } else {
            addMusic(this.form).then(() => {
              this.$message.success("新增成功")
              this.open = false;
              this.getList();
              this.reset();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项？').then(function () {
        return deleteMusics(ids);
      }).then(() => {
        this.getList();
        this.$message("删除成功");
      }).catch(() => {
      });
    },
    // 文件上传操作
    handleUploadSuccess(res, file, fileList, type) {
      if (res.code !== 200) this.$message.error((res.msg))
      else {
        if (type === 'AVATAR') {
          this.form.avatar = res.data
        } else {
          this.form.content = res.data
        }
      }
    },
    handleBeforeUpload(file, type) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      let isImage
      let isDocument
      if (type === 'AVATAR') {
        isImage = file.type.startsWith('image')
        if (!isImage) {
          this.$message.error('上传图片格式!')
        }
      } else {
        console.log(file)
        isDocument = file.type.includes('audio')
        if (!isDocument) {
          this.$message.error('上传文档格式!')
        }
      }
      return (isImage || isDocument) && isLt10M
    },
    handleRemove(file, fileList, type) {
      if (type === 'AVATAR') {
        this.form.avatar = ''
      } else {
        this.form.content = ''
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
      console.log(`当前页: ${val}`);
    },
    goto(url) {
      window.location.href = url
    },
    handleComment(row) {
      this.$router.push({
        path: '/music/comment',
        query: {
          songId: row.id
        }
      });
    }
  }
}
</script>
<style scoped lang="scss">
$size: 150px;
$color: #DCDFE6;

.avatar-uploader {
  width: $size;
  height: $size;
  border: 1px dashed $color;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  font-size: 28px;
  color: rgba(96, 98, 102);
}

.img {
  margin-top: 10px;
  width: 100%;
  height: 100%;
  border-radius: 5px;
}

.right-toolbar {
  float: right;
}
</style>
